#include "loginwindow.h"
#include "ui_loginwindow.h"

#include <QMetaObject>
#include <QThread>
#include <QMessageBox>

//#define WIN32_LEAN_AND_MEAN
//#include <winsock2.h>
#include <windows.h>
#include <objbase.h>

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
LoginWindow::LoginWindow(SdkManager* sdk_mgr, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::LoginWindow)
    , m_sdk_mgr(sdk_mgr)
{
    ui->setupUi(this);

	m_sdk_mgr->RegisterLoginResultHandler([this](bool result) {
		OnLoginResult(result);
	});

    connect(ui->pushButton_login, &QPushButton::clicked, this, &LoginWindow::OnLoginButtonClicked);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
LoginWindow::~LoginWindow()
{
	m_sdk_mgr->RegisterLoginResultHandler(nullptr);
	
    delete ui;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void LoginWindow::OnLoginButtonClicked()
{
    qDebug() << "onLoginButtonClicked";

    m_user_id = ui->lineEdit_user->text().toStdString();

    if (m_user_id.empty()) {
        QMessageBox::warning(this, "登录失败", "UserID 不能为空！");
    } else {
        if (!m_sdk_mgr->Login(m_user_id)) {
            QMessageBox::warning(this, "登录失败", "SDK返回错误");
        }
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void LoginWindow::OnLoginResult(bool result)
{
    if (result) {
        LoginSuccess(m_user_id);
    } else {
        QMessageBox::warning(this, "登录失败", "SDK返回错误");
    }
}
